package com.elite.groovy.callback

import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.HttpEntity
import org.apache.http.HttpHost
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class autoQnFirstPreCall implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(autoQnFirstPreCall.class)
	@Override
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		log.debug("开始启动青牛预测外呼首拨名单下发");
		JSONObject result = new JSONObject();
		long startTime=System.currentTimeMillis();
		try {
			//获取配置文件中配置好的企业号、代理ip及端口
			PropertiesUtil cfg = new PropertiesUtil();
			def Te_entId = cfg.readValue("QingNiu.EntId");
			String proxyIp = cfg.readValue("QingNiu.ProxyIP");
			int proxyPort=0;
			if(cfg.readValue("QingNiu.ProxyPort")!=null&&cfg.readValue("QingNiu.ProxyPort")!="") {
				proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
			}

			def id=UUID.randomUUID().toString();
			//将已经启动下发的、并且批次规则大于等于推送时间的未加入过临时表的批次标记好id
			StringBuffer bf = new StringBuffer("update Inflow_rule_configuration set state='2',guid='"+ id +"'" );
			bf.append("where to_date(to_char(sysdate, 'yyyy-mm-dd'), 'yyyy-mm-dd')>=Inflow_date and state='1' ");
			int row1=eliteBean.update(bf.toString(),"dataSource");
			//log.debug("标记:"+row1);
			//log.debug("启动批次sql:"+bf.toString());
			//根据标记的id将customer表中对应的需要推送至青牛的数据查询出来全部添加到临时表中(id插入车的那条)，数据类型标记为首拨类型（1）
			log.debug("新增可推送批次数量:"+row1);
			if(row1>0) {
			def seleteSQL1="insert into list_push_temporary (id, customer_guid, customer_name,  mobile, tel_1,  atel_1, atel_2, atel_3, atel_4, createddate,  createdby, in_enddate, custlist, activity_name, send_type,objective_guid) select sys_guid(),  c.customer_guid, c2.customername, c2.mobile,  c2.tel_1,   c2.atel_1,   c2.atel_2,     c2.atel_3,  c2.atel_4,  sysdate,  'SELITE',  c.in_enddate,  c.stringfield1,  b2.first_call_activity,   '1',objective_guid  from elitetask e left join customer c  on e.customer_guid = c.customer_guid  left join customer c2 on c.parent_guid = c2.customer_guid inner join Inflow_rule_configuration b   on c.stringfield1 = b.custlist_name inner join batch_configuration b2  on b.Activity_name = b2.id left join tabccontacthis_his ta  on c.customer_guid = ta.customer_guid left join authority_relationship a on e.handlegroup_id = a.lower where e.handleby_id is null and c.customertype2_id = '000002' and b.guid = '"+id+"'  and ta.customer_guid is null and c.customer_guid not in   (select distinct customer_guid  from List_Push_History lh left join custlists cl   on lh.Custlist = cl.CUSTLIST_XXX   where send_type = '1') and (b2.is_holiday_floor = 1 or  (b2.is_holiday_floor = 0 and   e.handlegroup_id not in   (select cf.createdgroup    from c_freedate cf  where cf.freedate = trunc(sysdate)))  and      (b2.is_holiday_floor = 0 and   a.higher not in (select cf.createdgroup  from c_freedate cf  where cf.freedate = trunc(sysdate))))";
            int row2=eliteBean.update(seleteSQL1,"dataSource");
			log.debug("批次名单加入临时表SQL:"+seleteSQL1);
		    log.debug("批次名单加入临时表数量:"+row2);

			}

			//查询当天是否为节假日
			//def seleteSQL3="select case when count(*) > 0 then '1'  else '0' end con from c_freedate where freedate = //to_date(to_char(sysdate,'yyyy-mm-dd'),'yyyy/mm/dd')";
			//def result1=eliteBean.chaxun_sql(seleteSQL3, "dataSource");
			//def queryMap2=result1[0];
			//def holiyday = queryMap2.get("CON");
			//log.debug("当天是否节假日:"+holiyday);

			//将已经加入到临时表的当日可推送首拨批次全部查询出来
			StringBuffer bff = new StringBuffer("select i.id,i.custlist_name,b.first_call_activity,i.inflow_count,b.is_holiday_floor ");
			bff.append("from Inflow_rule_configuration i left join batch_configuration b  on i.Activity_name = b.id  where i.state='2' ");
			bff.append("  and to_date(to_char(inflow_date, 'yyyy-mm-dd'), 'yyyy-mm-dd') <= to_date(to_char(sysdate, 'yyyy-mm-dd'), 'yyyy-mm-dd') ");
			List resultlist=eliteBean.chaxun_sql(bff.toString(), "dataSource");
			JSONArray jsonArray=JSONArray.fromObject(resultlist);
			int ListNum = jsonArray.size();
			log.debug("可推送批次条数:"+ListNum);
			int count = 0;
			if(ListNum>0){
				String selectSQL3="select WEBSERVICEURL from sysc_interface where webtype='QN_MDDR'";
				
				def postURL2=eliteBean.chaxun_sql(selectSQL3, "dataSource");
				//log.debug(postURL2);
				def httpURL=postURL2[0].get("WEBSERVICEURL");
				//log.debug("青牛地址:"+httpURL);

				List customerGuid = new ArrayList() ;
				JSONObject dataObject2 = null;
				//将每个批次按照其批次规则中配置的当日应下发条数、是否节假日流入在临时表中标记出对应数量并且批次类型为首拨的数据,临时表数据状态Is_push标记为待下发(0)
				for(int i=0;i<ListNum;i++) {
					dataObject2 = jsonArray.getJSONObject(i);
					def custlist_name=GetJV(dataObject2, "CUSTLIST_NAME");//批次
					def inflow_count=GetJV(dataObject2, "INFLOW_COUNT");//条数
					def is_holiday_floor=GetJV(dataObject2, "IS_HOLIDAY_FLOOR");//是否节假日流入配置

					//log.debug("开始推送批次:"+custlist_name);
					//log.debug("每日流入条数：" + inflow_count);
					//如果当天为节假日且批次规则中是否节假日流入不等于1则该批次当日不下发跳出循环
					//if(is_holiday_floor=='0') {continue;}
					StringBuffer sbff = new StringBuffer("update list_push_temporary set Is_push='0' ");
					sbff.append("where customer_guid in (select customer_guid from (select l.customer_guid from ");
					sbff.append("list_push_temporary l left join elitetask e on l.objective_guid=e.objective_guid inner join Inflow_rule_configuration b on e.custlistname = b.custlist_name inner join batch_configuration b2  on b.Activity_name = b2.id left join authority_relationship a on e.handlegroup_id = a.lower where l.custlist='"+custlist_name+"' and l.send_type='1' ");
					sbff.append("and (b2.is_holiday_floor = 1 or  (b2.is_holiday_floor = 0 and   e.handlegroup_id not in   (select cf.createdgroup    from c_freedate cf  where cf.freedate = trunc(sysdate)))  and      (b2.is_holiday_floor = 0 and   a.higher not in (select cf.createdgroup  from c_freedate cf  where cf.freedate = trunc(sysdate)))) order by in_enddate asc) where rownum<="+inflow_count+") ")	;
					int row3=eliteBean.update(sbff.toString(),"dataSource");
					//log.debug(custlist_name+"首拨推送条数为:"+row3);
					//log.debug(custlist_name+"首拨推送条数sql:"+sbff.toString());

					int sendNum=2700; //每批数据分批推送条数
					int con = Math.ceil(row3/sendNum);
					
					for(int q=1;q<=con;q++) {
						def updateSQL1="update list_push_temporary set Is_push='1' where Is_push='0' and send_type='1' and rownum<='"+sendNum+"'";
						int row4=eliteBean.update(updateSQL1,"dataSource");
						//log.debug("修改下发状态Sql:"+updateSQL1)

						//查询出所有标记好的待下发的首播数据
						String sqls = "select l.customer_guid custId,"+Te_entId+" ENTID,l.activity_name CALLLISTNAME,l.customer_guid recordKey,l.mobile,l.tel_1,l.atel_1,l.atel_2,l.atel_3,l.atel_4,l.objective_guid from list_push_temporary l left join elitetask e on l.objective_guid=e.objective_guid inner join Inflow_rule_configuration b on e.custlistname = b.custlist_name inner join batch_configuration b2  on b.Activity_name = b2.id left join authority_relationship a on e.handlegroup_id = a.lower where  l.Is_push = '1'and l.send_type = 1 and e.objective_guid is not null and (b2.is_holiday_floor = 1 or  (b2.is_holiday_floor = 0 and   e.handlegroup_id not in   (select cf.createdgroup    from c_freedate cf  where cf.freedate = trunc(sysdate)))  and      (b2.is_holiday_floor = 0 and   a.higher not in (select cf.createdgroup  from c_freedate cf  where cf.freedate = trunc(sysdate)))) order by in_enddate asc ";
						def resultlist2= eliteBean.chaxun_sql(sqls, "dataSource");
						//log.debug("待下发的首拨数据sql:"+buff.toString());
						JSONArray jsonArray2=JSONArray.fromObject(resultlist2);
						int ListNum2 = jsonArray2.size();
						JSONArray arr = new JSONArray();
						JSONObject obj = new JSONObject();

						for(int j=0;j<ListNum2;j++) {
							JSONObject dataObject = jsonArray2.getJSONObject(j);
							def cust_id=GetJV(dataObject, "CUSTID");
							def entId=GetJV(dataObject, "ENTID");
							def activity_id=GetJV(dataObject, "CALLLISTNAME");
							//String activity_id=new String(activity.getBytes("utf-8"),"iso-8859-1");
							def recordKey=GetJV(dataObject, "RECORDKEY");
							def objectiveGuid = GetJV(dataObject, "OBJECTIVE_GUID");
							if(objectiveGuid==null || objectiveGuid=="") {
								continue;
							}
							JSONObject phoneNumbers = new JSONObject();
							phoneNumbers.put("phoneNumber1", GetJV(dataObject, "MOBILE"));
							phoneNumbers.put("phoneNumber2", GetJV(dataObject, "TEL_1"));
							phoneNumbers.put("phoneNumber3", GetJV(dataObject, "ATEL_1"));
							phoneNumbers.put("phoneNumber4", GetJV(dataObject, "ATEL_2"));
							phoneNumbers.put("phoneNumber5", GetJV(dataObject, "ATEL_3"));
							phoneNumbers.put("phoneNumber6", GetJV(dataObject, "ATEL_4"));

							obj.put("custId", cust_id+","+objectiveGuid);
							obj.put("entId", entId);
							obj.put("callListName", activity_id);
							obj.put("recordKey", recordKey);
							obj.put("phoneNumbers", phoneNumbers);
							obj.put("exData7",id);
							obj.put("exData5",objectiveGuid);
							obj.put("exData6",objectiveGuid);
							arr.add(obj);
						}
						JSONObject objtwo = new JSONObject();
						objtwo = new JSONObject();
						objtwo.put("batchId", id);
						objtwo.put("total", ListNum2);
						objtwo.put("data", arr);


						long time=System.currentTimeMillis();
						//String reJson =sendHttpPost(httpURL, objtwo.toString().trim(), proxyIp,proxyPort)
						
						def reJson = HttpClientProxy.sendPost(httpURL, objtwo.toString(),proxyIp,proxyPort);
						JSONObject json = new JSONObject().fromObject(reJson);
						//log.debug("首拨名单推送调用返回结果:"+reJson);
						long etime=System.currentTimeMillis();
						//log.debug("接口请求时间："+(etime-time));
						
						
						String code=json.code;
						StringBuffer sql = new StringBuffer("insert into list_push_history ");
						sql.append("(id,batch_id,customer_guid,is_flag,activity_name,custlist,");
						sql.append("createddate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid) ");
						sql.append("select sys_guid(),id,customer_guid,'"+code+"',activity_name,custlist,");
						sql.append("sysdate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid ");
						sql.append("from list_push_temporary where is_push='1' and send_type='1'");
						int row7=eliteBean.update(sql.toString(),"dataSource");
						//log.debug("本次推送记录至历史表数量:"+row7);
						count+=row7;
						
						
						
						if(json.code == "0") {
							def deleteSQL1="delete from list_push_temporary where is_push='1' and send_type='1'";
							int row6=eliteBean.update(deleteSQL1,"dataSource");
							log.debug("本次推送清除临时表数量:"+row6);

						}
					}
					
					String selectSQL4="select count(*) CONTWO from list_push_temporary where custlist='"+custlist_name+"' and send_type='1'";
					def result2=eliteBean.chaxun_sql(selectSQL4, "dataSource");
					def queryMap3=result2[0];
					def row7 = queryMap3.get("CONTWO");
					//log.debug(custlist_name+"剩余数量:"+row7);
					String updateState="";
					if(row7==0) {
						updateState=",state='3'";
					};
					//推送后更新配置表中剩余首拨数量，当临时表中相关批次剩余首拨为0则将状态更新为3表示该首拨批次已全部推送
					def updateSQL1="update Inflow_rule_configuration set LAVENUM='"+row7+"'"+ updateState +" where custlist_name='"+custlist_name+"'";
					int row6=eliteBean.update(updateSQL1,"dataSource");
					//log.debug("本次推送清除临时表数量:"+row6);
					//更新批次管理当前可用名单的数量
					//def updSql = "update custlists set assignamount="+count+",notassignamount =numberofcustomer-"+count+" where custlist_xxx = //'"+custlist_name+"'";
					//int row =eliteBean.update(updSql,"dataSource");
					//log.debug("本次推送后当前可用名单的数量:"+row);
				}
				long endTime=System.currentTimeMillis();
				result.put("code", 1);
				result.put("msg", "处理完成、调用处理时长(毫秒):" + (endTime - startTime)+"共推送名单:"+count);
				
				log.debug("青牛预测外呼首拨名单下发结束");

			}else {
				result.put("code", 1007);
				result.put("msg", "未找到符合条件的批次");
			}

		} catch (Exception e) {
			result.put("code", 1008);
			result.put("msg", e.getMessage());
		}
	}

	public static String sendHttpPost(String url, String JSONBody, String pIP, int pPort) throws Exception {
		CloseableHttpClient httpclient = null
		HttpHost proxy=null
		if (pIP == null || pIP.length() <= 0) {
			httpclient = HttpClients.createDefault()
		} else {
			// 设置代理IP、端口、协议（请分别替换）
			proxy = new HttpHost(pIP, pPort, "http")
		}
		// 把代理设置到请求配置
		//RequestConfig reqConfig = RequestConfig.custom().setProxy(proxy).setSocketTimeout(50000).setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
		RequestConfig reqConfig = RequestConfig.custom().setProxy(proxy).build()

		// 实例化CloseableHttpClient对象
		httpclient = HttpClients.custom().setDefaultRequestConfig(reqConfig).build()

		HttpPost httpPost = new HttpPost(url)
		httpPost.addHeader("Content-Type", "application/json")
		httpPost.setEntity(new StringEntity(JSONBody))
		CloseableHttpResponse response = httpclient.execute(httpPost)
		HttpEntity entity = response.getEntity()
		String responseContent = EntityUtils.toString(entity, "UTF-8")
		response.close()
		httpclient.close()
		return responseContent
	}
   

	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null
		try {
			Rev_Value = inJson.getString(getKey)
			//log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey))
				//log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = ""
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = ""
			}
		}
		return Rev_Value
	}

}